import 'package:flutter/material.dart';
import 'package:flutter_nb_net/flutter_net.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:flutter_slidable/flutter_slidable.dart';
import 'package:go_router/go_router.dart';
import 'package:tracker/common/log/x_logger.dart';
import 'package:tracker/common/model/base_resp.dart';
import 'package:tracker/pages/home/fence/model/fence_list_resp.dart';
import 'package:tracker/provider/global_provider.dart';
import 'package:tracker/router/router_manager.dart';
import 'package:tracker/theme/app_theme.dart';
import 'package:tracker/utils/color_utils.dart';
import 'package:tracker/utils/num_utils.dart';
import 'package:tracker/utils/toast_utils.dart';

class FencePage extends ConsumerStatefulWidget {
  const FencePage({super.key});

  @override
  ConsumerState<FencePage> createState() => _FencePageState();
}

class _FencePageState extends ConsumerState<FencePage> {
  List<FenceData>? fenceList = [];

  _fetchFenceList() async {
    final deviceInfo = ref.watch(deviceInfoProvider);
    final queryParams = {
      'imei': deviceInfo.imei,
    };
    final res = await post<FenceListResp, FenceListResp>('/electronic-fence/list',
        data: queryParams, decodeType: FenceListResp());
    res.when(success: (resp) {
      if (resp.code == 200) {
        setState(() {
          fenceList = resp.data!;
        });
      } else {
        ToastUtils.showToast(resp.msg ?? '获取围栏列表失败');
      }
    }, failure: (String msg, int code) {
      ToastUtils.showToast('获取围栏列表失败');
    });
  }

  Widget _buildList() {
    return ListView.builder(
        itemCount: fenceList?.length ?? 0,
        itemBuilder: (BuildContext context, int index) {
          final fence = fenceList?[index];
          final longitude = NumUtils.formatNum(fence?.longitude ?? 0, format: '0.000000');
          final latitude = NumUtils.formatNum(fence?.latitude ?? 0, format: '0.000000');
          final radius = NumUtils.formatNum(
            fence?.radius ?? 0,
          );
          return Slidable(
            endActionPane: ActionPane(
              motion: const ScrollMotion(),
              children: [
                CustomSlidableAction(
                  key: ValueKey(fence?.id),
                  onPressed: (context) async {
                    final deviceInfo = ref.read(deviceInfoProvider);
                    final queryParams = {
                      'imei': deviceInfo.imei,
                      'id': fence?.id,
                    };
                    final url = '/electronic-fence/${fence?.id}';
                    final res = await delete<BaseResp, BaseResp>(url, data: queryParams, decodeType: BaseResp());
                    res.when(success: (resp) {
                      if (resp.code == 200) {
                        ToastUtils.showToast('删除成功');
                        setState(() {
                          fenceList?.removeAt(index);
                        });
                      } else {
                        ToastUtils.showToast(resp.msg ?? '删除失败');
                      }
                    }, failure: (String msg, int code) {
                      ToastUtils.showToast('删除失败');
                    });
                  },
                  backgroundColor: Colors.transparent,
                  padding: const EdgeInsets.only(top: 20),
                  child: const _FenceActionButton(label: '删除'),
                ),
              ],
            ),
            child: GestureDetector(
              onTap: () async {
                final result = await context.push<bool>(RouterManager.createFence, extra: fence);
                if (result == true) {
                  _fetchFenceList();
                }
              },
              child: _FenceListTile(
                title: fence?.name ?? '',
                subtitle: '经度: ${longitude} 纬度: ${latitude} 半径: ${radius}米',
              ),
            ),
          );
        });
  }

  Widget _buildCreateButton() {
    return Positioned(
      bottom: 20,
      left: 20,
      right: 20,
      child: ElevatedButton(
        onPressed: () async {
          XLogger.debug('创建围栏');
          // 创建围栏
          final refresh = await context.push<bool>(RouterManager.createFence);
          if (refresh == true) {
            _fetchFenceList();
          }
        },
        style: ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(12),
          ),
          backgroundColor: AppTheme.themeConfig.primaryColor,
        ),
        child: const Text('创建围栏', style: TextStyle(color: Colors.white)),
      ),
    );
  }

  @override
  void initState() {
    WidgetsBinding.instance?.addPostFrameCallback((timeStamp) {
      _fetchFenceList();
    });
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(
          '围栏',
          style: TextStyle(color: Colors.white),
        ),
        centerTitle: true,
        backgroundColor: AppTheme.themeConfig.primaryColor,
        elevation: 0,
        iconTheme: const IconThemeData(color: Colors.white),
      ),
      backgroundColor: ColorUtils.hexToColor('#F5F5F5'),
      body: Stack(
        children: [
          _buildList(),
          _buildCreateButton(),
        ],
      ),
    );
  }
}

class _FenceActionButton extends StatelessWidget {
  final String label;
  const _FenceActionButton({required this.label});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60,
      decoration: BoxDecoration(
        color: Colors.red,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Center(
        child: Text(
          label,
          style: const TextStyle(
            fontSize: 15,
            color: Colors.white,
          ),
        ),
      ),
    );
  }
}

class _FenceListTile extends StatelessWidget {
  final String title;
  final String subtitle;
  const _FenceListTile({required this.title, required this.subtitle});

  @override
  Widget build(BuildContext context) {
    return Container(
      height: 60,
      margin: const EdgeInsets.only(left: 20, right: 20, top: 20),
      decoration: BoxDecoration(
        color: Colors.white,
        borderRadius: BorderRadius.circular(12),
      ),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.spaceAround,
        children: [
          Row(
            children: [
              Expanded(
                child: Container(
                  margin: const EdgeInsets.only(left: 12),
                  child: Text(
                    '围栏名称：${title}',
                    style: TextStyle(
                      fontSize: 17,
                      color: AppTheme.themeConfig.primaryTextColor,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
            ],
          ),
          Row(
            children: [
              Expanded(
                child: Container(
                  margin: const EdgeInsets.only(left: 12),
                  child: Text(
                    subtitle,
                    style: TextStyle(
                      fontSize: 13,
                      color: AppTheme.themeConfig.infoTextColor,
                    ),
                    overflow: TextOverflow.ellipsis,
                  ),
                ),
              ),
            ],
          )
        ],
      ),
    );
  }
}
